﻿using DataAccess;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DataEntity;
using IntelligentQuery.Model;

namespace WebUI.Controllers
{
    public class ListDetailManageController : Controller
    {
        //
        // GET: /ListDetailManage/
        private DataContext db = new DataContext();

        /// <summary>
        /// 入库单物品明细 
        /// </summary>
        private IEntityRepository<OffPurchaseBillDetail> PurchaseBillDetailRepository;

        /// <summary>
        /// 物品表
        /// </summary>
        private IEntityRepository<OffGoods> GoodsRepository;

        public ListDetailManageController()
        {
            PurchaseBillDetailRepository = new EntityRepository<OffPurchaseBillDetail>(db);
            GoodsRepository = new EntityRepository<OffGoods>(db);
        }
        public ActionResult Index(int purchaseBillID)
        {
            ViewBag.PurchaseBillID = purchaseBillID;
            return View();
        }
        #region  json返回数据
        /// <summary>
        /// 物品明细
        /// </summary>
        /// <param name="page"></param>
        /// <param name="rows"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult PurchaseBillDetailJson(int purchaseBillID,int? page, int? rows, string model)
        {
            int Page = page ?? 1;
            int Rows = rows ?? 10;
            QueryModel QModel = null;
            Dictionary<string, object> JsonObj = new Dictionary<string, object>();
            if (!string.IsNullOrWhiteSpace(model))
            {
                QModel = IntelligentQuery.AjaxQueryConverter.ToQueryModel(model);
            }


            var pbillDetail = PurchaseBillDetailRepository.Get(QModel).Where(n=>n.OffPurchaseBillID==purchaseBillID).ToList();

            JsonObj.Add("total", pbillDetail.Count());
            JsonObj.Add("rows", pbillDetail.OrderByDescending(p => p.ID)
                    .Skip((Page - 1) * Rows)
                   .Take(Rows).Select(s => new { s.ID, s.Remark, s.AfterTaxPrice, s.OffGoods.Name, s.OffGoods.Unit, s.Quantity, s.Price, PurchaseBillName=s.OffPurchaseBill.Name,s.OffPurchaseBillID,s.OffGoodsID,GoodsClassName=s.OffGoods.OffGoodsClass.Name}));


            return JsonHelper.JsonEx(JsonObj);
        }

        #endregion
        #region 操作数据
        /// <summary>
        /// 新建/编辑页
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult CreateEdit(int purchaseBillID, int id = 0)
        {
            var model = new OffPurchaseBillDetail();
            model.OffPurchaseBillID = purchaseBillID;
            if (id != 0)
            {
                model = PurchaseBillDetailRepository.GetByKey(id);
            }
            return PartialView(model);
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="role"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Save(OffPurchaseBillDetail model)
        {
            try
            {
                
                if (model.ID == 0)
                {
                    model.OffGoods = null;
                    model.OffPurchaseBill = null;
                    PurchaseBillDetailRepository.Insert(model);
                    var goods = GoodsRepository.Get(n => n.ID == model.OffGoodsID).FirstOrDefault();
                    if (goods != null)
                    {
                        var inventory = goods.Inventory;
                        
                        goods.Inventory = goods.Inventory + model.Quantity;
                        goods.AverageAfterTaxPrice = (inventory + model.Quantity)!=0?(goods.AverageAfterTaxPrice * inventory + model.Quantity * model.AfterTaxPrice) / (decimal)(inventory + model.Quantity):0;
                        goods.AveragePerPrice = (inventory + model.Quantity)!=0?(goods.AveragePerPrice * inventory + model.Quantity * model.Price) / (decimal)(inventory + model.Quantity):0;
                        GoodsRepository.Update(goods);
                    }
                }
                else
                {
                    OffPurchaseBillDetail billDetail = PurchaseBillDetailRepository.GetByKey(model.ID);
                    var goods = GoodsRepository.Get(n => n.ID == billDetail.OffGoodsID).FirstOrDefault();
                    if (goods != null)
                    {
                        var inventory = goods.Inventory;
                        goods.Inventory = goods.Inventory -billDetail.Quantity;
                        goods.AverageAfterTaxPrice = (inventory - billDetail.Quantity)!=0?(goods.AverageAfterTaxPrice * inventory - billDetail.Quantity * billDetail.AfterTaxPrice) / (decimal)(inventory - billDetail.Quantity):0;
                        goods.AveragePerPrice = (inventory - billDetail.Quantity)!=0?(goods.AveragePerPrice * inventory - billDetail.Quantity * billDetail.Price) / (decimal)(inventory - billDetail.Quantity):0;
                        GoodsRepository.Update(goods);
                    }
                   
                    billDetail.OffGoodsID = model.OffGoodsID;
                    billDetail.Price = model.Price;
                    billDetail.Quantity = model.Quantity;
                    billDetail.AfterTaxPrice = model.AfterTaxPrice;
                    billDetail.Remark = model.Remark;
                    var newgoods = GoodsRepository.Get(n => n.ID == model.OffGoodsID).FirstOrDefault();
                    if (newgoods != null)
                    {
                        var inventory = newgoods.Inventory;
                        newgoods.Inventory = newgoods.Inventory + model.Quantity;
                        newgoods.AverageAfterTaxPrice = (inventory + model.Quantity)!=0?(newgoods.AverageAfterTaxPrice * inventory + model.Quantity * model.AfterTaxPrice) / (decimal)(inventory + model.Quantity):0;
                        newgoods.AveragePerPrice = (inventory + model.Quantity)!=0?(newgoods.AveragePerPrice * inventory + model.Quantity * model.Price) / (decimal)(inventory + model.Quantity):0;
                        GoodsRepository.Update(newgoods);
                    }
                    PurchaseBillDetailRepository.Update(billDetail);
                  
                }
                


                return Json(new { success = true });
            }
            catch (Exception e)
            {
                return Json(new { msg = e.Message });
            }
        }
        /// <summary>
        /// 单个删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult SingleDelete(int id)
        {
            try
            {
                var billDetail = PurchaseBillDetailRepository.GetByKey(id);
                var goods = GoodsRepository.Get(n => n.ID == billDetail.OffGoodsID).FirstOrDefault();
                if (goods != null)
                {
                    var inventory = goods.Inventory;
                    goods.Inventory = goods.Inventory-billDetail.Quantity;

                    goods.AverageAfterTaxPrice = (inventory - billDetail.Quantity)!= 0? (goods.AverageAfterTaxPrice * inventory - billDetail.Quantity * billDetail.AfterTaxPrice) / (decimal)(inventory - billDetail.Quantity) : 0;
                    goods.AveragePerPrice = (inventory - billDetail.Quantity)!=0 ? (goods.AveragePerPrice * inventory - billDetail.Quantity * billDetail.Price) / (decimal)(inventory - billDetail.Quantity) : 0;
                    GoodsRepository.Update(goods);
                }
                PurchaseBillDetailRepository.Delete(billDetail);

                return Json(new { success = true });
            }
            catch (Exception e)
            {
                return Json(new { msg = e.Message });
            }
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult BatchDelete(string ids)
        {
            try
            {
                
                List<string> list_id = ids.Split(',').ToList();
                var billDetailList = PurchaseBillDetailRepository.Get().ToList().Where(u => list_id.Contains(u.ID.ToString())).ToList();
                foreach (var billDetail in billDetailList)
                {
                    var goods = GoodsRepository.Get(n => n.ID == billDetail.OffGoodsID).FirstOrDefault();
                    if (goods != null)
                    {
                        var inventory = goods.Inventory;
                        goods.Inventory = goods.Inventory - billDetail.Quantity;

                        goods.AverageAfterTaxPrice = (inventory - billDetail.Quantity)!=0?(goods.AverageAfterTaxPrice * inventory - billDetail.Quantity * billDetail.AfterTaxPrice) / (decimal)(inventory - billDetail.Quantity):0;
                        goods.AveragePerPrice = (inventory - billDetail.Quantity)!=0?(goods.AveragePerPrice * inventory - billDetail.Quantity * billDetail.Price) / (decimal)(inventory - billDetail.Quantity):0;
                        GoodsRepository.Update(goods);
                    }
                   
                }
                
                PurchaseBillDetailRepository.Delete(billDetailList);
                return Json(new { success = true });
            }
            catch (Exception e)
            {
                return Json(new { msg = e.Message });
            }
        }


        #endregion
       
        
    }
}
